package com.example.tliasmanagement.interceptor;

import com.example.tliasmanagement.util.JwtUtils;
import com.example.tliasmanagement.util.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 进入controller前执行，先进入preHandle，如果这个方法返回true，进入controller，如果是false，不进入controller
        log.info("preHandle:{}", request.getRequestURI());

        String requestURI = request.getRequestURI();
        // 判断是否是登录请求
        if(requestURI.indexOf("/login") >= 0){
            // 放行
            return true;
        }
        // 从请求头中获取token
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            // 禁止访问，跳转到登录
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        // 校验token
        try{
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id", Integer.class);
            String username = claims.get("username", String.class);
            // 向当前线程中保存了一个UserInfo
            UserThreadLocal.setUserInfo(new UserThreadLocal.UserInfo(id, username ));
            // token是合法的
            // 放行
            return true;
        }catch(Exception e){
            log.error(e.getMessage(), e);
            // 禁止访问，跳转到登录
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // controller执行完成以以后，会执行这个方法。
        // 如果controller执行的时候出现异常，这个方法不执行
        log.info("postHandle:{}", request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 页面渲染完成以后再执行
        // 就算controller执行的时候出现异常，这个方法也要执行
        log.info("afterCompletion:{}", request.getRequestURI());
        // 从当前线程中删除UserInfo
        UserThreadLocal.removeUserInfo();
    }
}